<?php

class stSocialMediaToolboxController extends stcontroller_2_1 {

    public function __construct($config) {
        parent::__construct($config);
        $this->config ['appDir'] = $this->config['pluginDir'] . 'applications/';
        session_start();
    }

    public function loadAdminCss() { // load more css custom here
        echo '<link href="' . $this->config ['backendCss'] . 'prettyphoto/prettyPhoto.css" rel="stylesheet" type="text/css" />' . "\n";
        echo "<link rel='stylesheet' href='" . $this->config['backendCss'] . "postcardStyle.css' type='text/css' media='all' />";
    }

    public function loadAdminScript() { // load more js custom here
        echo '<script type="text/javascript" src="' . $this->config ['backendScript'] . 'jquery.prettyPhoto.js"></script>';
        echo '<script type="text/javascript" src="' . $this->config ['backendScript'] . 'stSocialMediaToolboxCustom.js"></script>';
        echo '<script type="text/javascript" src="' . $this->config ['backendScript'] . 'jquery.imgareaselect.js"></script>';
    }

    public function loadAdminGlobalScript() {
        echo '<script type="text/javascript" src="' . $this->config ['backendScript'] . 'jquery.prettyPhoto.js"></script>';
        echo '<script type="text/javascript" src="' . $this->config ['backendScript'] . 'stSocialMediaGlobal.js"></script>';
        echo '<script type="text/javascript" src="' . $this->config ['backendScript'] . 'stSocialMediaToolbox.js"></script>';
        echo '<script type="text/javascript" src="' . str_replace('stSocialMediaToolbox', 'stSocialMediaToolbox/Toolboxes/stPublishToolbox', $this->config ['backendScript']) . 'jquery-ui-1.8.7.custom.min.js"></script>';
        echo '<script type="text/javascript" src="' . str_replace('stSocialMediaToolbox', 'stSocialMediaToolbox/Toolboxes/stPublishToolbox', $this->config ['backendScript']) . 'stPublishToolbox.js"></script>';
        echo '<script type="text/javascript" src="' . str_replace('stSocialMediaToolbox', 'stSocialMediaToolbox/Toolboxes/stPublishToolbox', $this->config ['backendScript']) . 'jquery-ui-timepicker-addon.js"></script>';
    }

    public function loadAdminGlobalCss() {
        echo '<link href="' . $this->config ['backendCss'] . 'st_ui.css" rel="stylesheet" type="text/css" />' . "\n";
        echo '<link href="' . $this->config ['backendCss'] . 'stGlobal.css" rel="stylesheet" type="text/css" />' . "\n";
        echo '<link href="' . $this->config ['backendCss'] . 'prettyphoto/prettyPhoto.css" rel="stylesheet" type="text/css" />' . "\n";
    }

    public function customAdminEnqueueScript() {
        parent::customAdminEnqueueScript();
    }

    public function loadCss() {
        //this is function import javascript
        parent::loadCss();
    }

    public function loadScript() {
        //this is function import javascript
        parent::loadScript();
    }

    public function activationPlugin() {
        // put your activation code here
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

        $table = $wpdb->prefix . "st_pluginperm";
        $structure = "CREATE TABLE IF NOT EXISTS $table (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `user_id` int(11) NOT NULL,
              `plugin_name` varchar(225) COLLATE utf8_unicode_ci NOT NULL,
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ;
        ";
        dbDelta($structure);
        $table = $wpdb->prefix . "st_user_log";
        $structure = "CREATE TABLE `$table` (
        `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
        `type` VARCHAR(255) NOT NULL ,
        `date` VARCHAR( 20 ) NOT NULL ,
        `username` VARCHAR(255) NOT NULL ,
        `browser` VARCHAR(255) NOT NULL ,
        `os` VARCHAR(255) NOT NULL ,
        `ip` VARCHAR(255) NOT NULL
        ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ";
        dbDelta($structure);

        $table = $wpdb->prefix . "st_social_user";
        $structure = "CREATE TABLE IF NOT EXISTS $table (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `user_id` int(11) NOT NULL,
              `user_email` varchar(225) COLLATE utf8_unicode_ci NOT NULL,
              `parent_id` int(11) NOT NULL DEFAULT '0',
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ;
        ";
        dbDelta($structure);

        $table = $wpdb->prefix . "st_options";
        $structure = "CREATE TABLE IF NOT EXISTS $table (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `user_id` int(11) NOT NULL,
              `option_name` varchar(225) COLLATE utf8_unicode_ci NOT NULL,
              `option_value` longtext NOT NULL,
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ;
        ";
        dbDelta($structure);

        $table = $wpdb->prefix . "st_cronjob_log";
        $structure = "CREATE TABLE IF NOT EXISTS $table (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `cronjob_name` varchar(225) COLLATE utf8_unicode_ci NOT NULL,
              `toolbox_name` varchar(225) COLLATE utf8_unicode_ci NOT NULL,
              `url` varchar(225) COLLATE utf8_unicode_ci NOT NULL,
              `status` smallint(1) NOT NULL DEFAULT '0',
              `ctime` datetime NOT NULL,
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ;
        ";
        dbDelta($structure);

        $table = $wpdb->prefix . "st_app_perm";
        $structure = "CREATE TABLE IF NOT EXISTS $table (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `user_id` int(11) NOT NULL,
              `app_name` varchar(225) COLLATE utf8_unicode_ci NOT NULL,
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ;
        ";
        dbDelta($structure);
        $wpdb->query("CREATE TABLE `st_coupon_contract` (
                    `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
                    `user_id` INT NOT NULL ,
                    `activated` DATE NOT NULL ,
                    `expire` DATE NOT NULL ,
                    `type` INT NOT NULL ,
                    `amount` INT NOT NULL ,
                    `contract` TEXT NOT NULL
                    )");
    }

    public function deactivationPlugin() {
        
    }

    protected function registerTabMenu() {
        if (isset($this->config['admin_tabs'])) {
            $user = get_current_user_id();
//            $user = get_user_by('id', $user);
//            if ($user->user_login != $this->config['userAdminName']) {
//                $this->config['disable_tabs'][] = 'userList';
//                $this->config['disable_tabs'][] = 'addOn';
//            }
            if (!user_can($user, 'read_private_pages')) {
                $this->config['disable_tabs'][] = 'userList';
                $this->config['disable_tabs'][] = 'addOn';
                $this->config['disable_tabs'][] = 'systemLog';
                $this->config['disable_tabs'][] = 'coupon';
                $this->config['disable_tabs'][] = 'setting';
                $this->config['disable_tabs'][] = 'appPermission';
                $this->config['disable_tabs'][] = 'cronjobLog';
            }
            //if(get_userdata($user)->wp_capabilities)
            if (!user_can($user, 'edit_dashboard')) {
                $this->config['disable_tabs'][] = 'addOn';
                $this->config['disable_tabs'][] = 'settingEmail';
                $this->config['disable_tabs'][] = 'systemLog';
                $this->config['disable_tabs'][] = 'userList';
                $this->config['disable_tabs'][] = 'coupon';
                $this->config['disable_tabs'][] = 'setting';
                $this->config['disable_tabs'][] = 'appPermission';
                $this->config['disable_tabs'][] = 'cronjobLog';
            }
            $this->setTabMenu($this->config['admin_tabs']);
        }
    }

    public function registerView() {
        $views = array(
            'cronjobWeeklyReport' => 'default'
        );
        $this->setView($views);
    }

    public function addOn() {
        parent::addOn();
        $this->view->headTitle1 = 'Installed Toolboxes';
    }

    public function app_setting() {
        global $wpdb, $current_user;
        $user = get_userdatabylogin($_POST['user']);
        $check = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}st_app_perm WHERE app_name = '{$_POST['app']}' AND user_id = {$user->ID}");
        switch ($_POST['app']) {
            case 'applications':
                $title = '"Form Builder"';
                break;
            case 'appPostcard':
                $title = '"Dynamic Postcard"';
                break;
            case 'appImageBuilder':
                $title = '"Image map builder"';
                break;
            case 'gallery_app':
                $title = '"Gallery"';
                break;
            case 'coupon':
                $title = '"Dashboard"';
                break;
        }
        if (!$check) {
            $arg = array(
                'status' => 'error',
                //'title' => 'Ad',
                'message' => __("User does not have permission", $config['plugin_name'])
            );
            echo $this->functions->sendMessage(json_encode($arg), 'appPermission');
            die;
        }
        $this->view->headIcon = 'icon_re';
        if ($_POST['app'] != 'coupon')
            $this->view->headTitle1 = $title . '  Permission Settings (User "' . $_POST['user'] . '")';
        else {
            $time = mktime(date_i18n("H"), date_i18n("i"), date_i18n("s"), date_i18n("n"), date_i18n("j"), date_i18n("Y"));
            $this->view->active_campaign = $wpdb->get_var("SELECT CouponTemplateName FROM st_coupon_templates WHERE user_id = {$user->ID} AND status = 1");
            $this->view->number_of_campaign = $wpdb->get_var("SELECT COUNT(*) FROM st_coupon_templates WHERE user_id = {$user->ID} ");
            $this->view->number_of_coupon = $wpdb->get_var("SELECT COUNT(*) FROM st_coupons WHERE user_id = $user->ID AND DATE(CouponGeneratedDateTime) >= '" . date_i18n('Y-m-d', $time - 24 * 3600) . "' AND DATE(CouponGeneratedDateTime) <= '" . date_i18n('Y-m-d') . "'");
            $this->view->total_number_of_coupon = $wpdb->get_var("SELECT COUNT(*) FROM st_coupons WHERE user_id = $user->ID");
            $this->view->total_sales = $wpdb->get_var("SELECT COUNT(*) FROM st_coupon_sales WHERE CouponID IN (SELECT CouponID FROM st_coupons WHERE user_id = $user->ID ) AND DATE(DateTime) >='" . date_i18n('Y-m-d', $time - 24 * 3600) . "' AND DATE(DateTime) <= '" . date_i18n('Y-m-d') . "'");
            $this->view->sales = $wpdb->get_var("SELECT COUNT(*) FROM st_coupon_sales WHERE CouponID IN (SELECT CouponID FROM st_coupons WHERE user_id = $user->ID )");
            $this->view->headTitle1 = 'Dashboard (User "' . $_POST['user'] . '")';
            $stFacebookToolbox_model = $this->loadmodel("stFacebookCouponTemplate");
            $args = array();
            $args['where'] = ' user_id = ' . $user->ID;
            $cur_page = $_REQUEST['cur_page'] ? $_REQUEST['cur_page'] : 1;
            $limit = $this->config['per_page'];
            $start = ($cur_page - 1) * $limit;

            $sort = $_REQUEST['sort'] ? $_REQUEST['sort'] : 0;
            $sort_type = $_REQUEST['sort_type'] ? $_REQUEST['sort_type'] : 0;
            if ($_REQUEST['sort']) {
                $args['order'] = array($sort, $sort_type);
            }
            $args['limit'] = array($start, $limit);
            //$args['limit'] = '';
            $results = $stFacebookToolbox_model->getRecords($args);
            $args['limit'] = '';
            $total = $stFacebookToolbox_model->countRecords($args);
            $pagination = $this->functions->pagination($start, $limit, $total, $cur_page, $this->actionName);

            $columns = array(
                'CouponTemplateName' => __('Campaign name', $this->config['plugin_name']),
                'ValidFromDateTime' => __('Valid From', $this->config['plugin_name']),
                'ValidToDateTime' => __('Valid To', $this->config['plugin_name']),
                'DiscountTypeID' => __('Number of coupons', $this->config['plugin_name']),
                'DiscountValue' => __('Number of customers', $this->config['plugin_name']),
                'SequenceNumber' => __('Number of sales', $this->config['plugin_name']),
                'is_fan' => __('Total sales amount', $this->config['plugin_name']),
            );
            register_column_headers('stFacebookToolbox_stFacebookToolbox', $columns);

            //initialize variable to view
            $this->view->results = $results;
            $this->view->pagination = $pagination;
            $this->view->model = $stFacebookToolbox_model;
        }


        $this->view->app = $_POST['app'];
        $this->view->user = $user->ID;
        $this->view->name = $_POST['user'];
    }

    //--- Phúc Nguyễn - Coupon 
    public function coupon() {
        global $wpdb, $current_user;
        $stFacebookToolbox_model = $this->loadmodel("stFacebookCoupon");
        $cur_page = $_REQUEST['cur_page'] ? $_REQUEST['cur_page'] : 1;
        $limit = $this->config['per_page'];
        $start = ($cur_page - 1) * $limit;

        $sort = $_REQUEST['sort'] ? $_REQUEST['sort'] : 0;
        $sort_type = $_REQUEST['sort_type'] ? $_REQUEST['sort_type'] : 0;
        if ($_REQUEST['sort']) {
            $args['order'] = array($sort, $sort_type);
        } else {
            $args['order'] = array('CouponID', 'DESC');
        } // sort
        $args['where'] = ' CouponTemplateID = ' . $_POST['template_id'];
        $args['limit'] = array($start, $limit);

        $results = $stFacebookToolbox_model->getRecords($args);
        $total = $wpdb->get_var("SELECT COUNT(*) FROM st_coupons WHERE CouponTemplateID = {$_POST['template_id']}");
        $pagination = $this->functions->pagination($start, $limit, $total, $cur_page, $this->actionName);

        $columns = array(
            'CouponUserID' => __('Customer', $this->config['plugin_name']),
            'CouponGeneratedDateTime' => __('Coupon Generated', $this->config['plugin_name']),
            'CouponTemplateID' => __('Campaign', $this->config['plugin_name']),
            'QCCodePath' => __('QC Code', $this->config['plugin_name']),
            'GeneratedCouponPath' => __('Coupon', $this->config['plugin_name']),
        );
        register_column_headers('stFacebookToolbox_stFacebookToolbox', $columns);
        $this->view->results = $results;
        $this->view->pagination = $pagination;
        $this->view->model = $stFacebookToolbox_model;
        $this->view->campain = $wpdb->get_var("SELECT CouponTemplateName FROM st_coupon_templates WHERE CouponTemplateID = {$_POST['template_id']}");
    }

    public function customer() {
        global $wpdb, $current_user;
        $stFacebookToolbox_model = $this->loadmodel("stFacebookCouponUser");
        $cur_page = $_REQUEST['cur_page'] ? $_REQUEST['cur_page'] : 1;
        $limit = $this->config['per_page'];
        $start = ($cur_page - 1) * $limit;
        $args['where'] = ' CouponUserID IN (SELECT CouponUserID FROM st_coupons WHERE CouponTemplateID = ' . $_POST['template_id'] . ') ';
        $sort = $_REQUEST['sort'] ? $_REQUEST['sort'] : 0;
        $sort_type = $_REQUEST['sort_type'] ? $_REQUEST['sort_type'] : 0;
        if ($_REQUEST['sort']) {
            $args['order'] = array($sort, $sort_type);
        }
        $args['limit'] = array($start, $limit);

        $results = $stFacebookToolbox_model->getRecords($args);
        $total = $stFacebookToolbox_model->countRecords();
        $pagination = $this->functions->pagination($start, $limit, $total, $cur_page, $this->actionName);

        $columns = array(
            'Name' => __('Name', $this->config['plugin_name']),
            'Gender' => __('Gender', $this->config['plugin_name']),
            'email' => __('Email', $this->config['plugin_name']),
            'BirthDate' => __('Birth Date', $this->config['plugin_name']),
            'HomeTown' => __('Location', $this->config['plugin_name']),
        );
        register_column_headers('stFacebookToolbox_stFacebookToolbox', $columns);

        //initialize variable to view
        $this->view->results = $results;
        $this->view->pagination = $pagination;
    }

    public function coupon_template_graphic() {
        $user = get_userdata($_GET['user']);
        $path = str_replace('wp-content/plugins/stSocialMediaToolbox/', '', $this->config ['pluginDir']);
        $this->view->graphic_config = include $path . 'coupon/config/graphicConfig.php';
        global $wpdb, $current_user;
        $this->view->headIcon = 'icon_re';
        $this->view->user = $_GET['user'];
        $this->view->headTitle1 = 'Coupon template graphics (User "' . $user->user_login . '")';
        require_once $this->config['pluginDir'] . '/Toolboxes/stFacebookToolbox/stPostcardsClassGallery.php';
        $stPostcardsClass = new stPostcardsClassGallery($this->config, $this->option);
        $stFacebookToolbox_model = $this->loadmodel("stFacebookCouponGraphic");
        if (isset($_POST['id']) && $_POST['edit'] == '1') {
            $result = $wpdb->get_results("SELECT * FROM st_coupon_template_graphics WHERE user_id = " . $_GET['user'] . " AND CouponTemplateGraphicsID = " . $_POST['id']);
            foreach ($result as $row) {
                $data['TemplatesGraphicsName'] = $row->TemplatesGraphicsName;
                $data['TemplatesGraphicsPath'] = $row->TemplatesGraphicsPath;
                $data['TemplatesPDFPath'] = $row->TemplatesPDFPath;
                $data['graphicConfig'] = $row->graphicConfig;
                $data['CouponTemplateGraphicsID'] = $_POST['id'];
            }
            $this->view->edit = json_encode($data);
        }
        if (isset($_POST['data'])) {
            if ($_POST['data']['id'] == '') {
                $data['TemplatesGraphicsName'] = $_POST['data']['name'];
                $data['user_id'] = $_POST['data']['user'];
                $data['graphicConfig'] = $_POST['data']['config'];
                $wpdb->insert('st_coupon_template_graphics', $data);
                $max = $wpdb->get_var("SELECT MAX(CouponTemplateGraphicsID) FROM st_coupon_template_graphics WHERE user_id = " . $_POST['data']['user']);
                $name = ('template_' . $_POST['data']['user'] . '_' . $max . '' . substr($_POST['data']['upload_file'], -4, 4));
                $pdf_name = 'pdf_' . $_POST['data']['user'] . '_' . $max . substr($_POST['data']['upload_pdf'], -4, 4);
                $thumb_name = ('template_' . $_POST['data']['user'] . '_' . $max . '-thumb' . substr($_POST['data']['upload_file'], -4, 4));
                $thumb_file = substr($_POST['data']['upload_file'], 0, strlen($_POST['data']['upload_file']) - 4) . '-thumb' . substr($_POST['data']['upload_file'], -4, 4);
                $stPostcardsClass->uploadGallery($_POST['data']['upload_file'], $name, $thumb_file, $thumb_name, 'fb-app-coupon/' . $_POST['data']['user']);
                $stPostcardsClass->uploadGallery($_POST['data']['upload_pdf'], $pdf_name, '', '', 'fb-app-coupon/' . $_POST['data']['user']);
                $data['TemplatesGraphicsPath'] = $_POST['data']['user'] . '/' . $name;
                $data['TemplatesPDFPath'] = $_POST['data']['user'] . '/' . $pdf_name;
                $wpdb->update('st_coupon_template_graphics', $data, array('CouponTemplateGraphicsID' => $max));
                unlink($_POST['data']['upload_file']);
                unlink($thumb_file);
                unlink($_POST['data']['upload_pdf']);
                $arg = array(
                    'status' => 'success',
                    'title' => 'Template uploaded',
                    'message' => __('New Template successfully uploaded', $config['plugin_name'])
                );
                echo $this->functions->sendMessage(json_encode($arg), 'coupon_template_graphic&user=' . $_POST['data']['user']);
                die;
            } elseif (intval($_POST['data']['edit']) == 1) {
                if ($_POST['data']['upload_file'] != $wpdb->get_var("SELECT TemplatesGraphicsPath FROM st_coupon_template_graphics WHERE CouponTemplateGraphicsID=" . $_POST['data']['id'])) {
                    $name = ('template_' . $_POST['data']['user'] . '_' . $_POST['data']['id'] . '' . substr($_POST['data']['upload_file'], -4, 4));
                    $thumb_name = ('template_' . $_POST['data']['user'] . '_' . $_POST['data']['id'] . '-thumb' . substr($_POST['data']['upload_file'], -4, 4));
                    $thumb_file = substr($_POST['data']['upload_file'], 0, strlen($_POST['data']['upload_file']) - 4) . '-thumb' . substr($_POST['data']['upload_file'], -4, 4);
                    $stPostcardsClass->deleteGallery('fb-app-coupon/' . $wpdb->get_var("SELECT TemplatesGraphicsPath FROM st_coupon_template_graphics WHERE CouponTemplateGraphicsID=" . $_POST['data']['id']));
                    $stPostcardsClass->uploadGallery($_POST['data']['upload_file'], $name, $thumb_file, $thumb_name, 'fb-app-coupon/' . $_POST['data']['user']);
                    $data['TemplatesGraphicsPath'] = $_POST['data']['user'] . '/' . $name;
                    unlink($thumb_file);
                    unlink($_POST['data']['upload_file']);
                }
                if ($_POST['data']['upload_pdf'] != $wpdb->get_var("SELECT TemplatesPDFPath FROM st_coupon_template_graphics WHERE CouponTemplateGraphicsID=" . $_POST['data']['id'])) {
                    $name = ('pdf_' . $_POST['data']['user'] . '_' . $_POST['data']['id'] . '' . substr($_POST['data']['upload_pdf'], -4, 4));
                    $stPostcardsClass->deleteGallery('fb-app-coupon/' . $wpdb->get_var("SELECT TemplatesPDFPath FROM st_coupon_template_graphics WHERE CouponTemplateGraphicsID=" . $_POST['data']['id']));
                    $stPostcardsClass->uploadGallery($_POST['data']['upload_pdf'], $name, '', '', 'fb-app-coupon/' . $_POST['data']['user']);
                    $data['TemplatesPDFPath'] = $_POST['data']['user'] . '/' . $name;
                    unlink($_POST['data']['upload_pdf']);
                }
                $data['TemplatesGraphicsName'] = $_POST['data']['name'];
                $data['user_id'] = $_POST['data']['user'];
                $data['graphicConfig'] = $_POST['data']['config'];
                $wpdb->update('st_coupon_template_graphics', $data, array('CouponTemplateGraphicsID' => $_POST['data']['id']));

                $arg = array(
                    'status' => 'success',
                    //'title'    => 'Image uploaded',
                    'message' => __('Edit successful', $config['plugin_name'])
                );
                echo $this->functions->sendMessage(json_encode($arg), 'coupon_template_graphic&user=' . $_POST['data']['user']);
            }
        }
        // short action handle
        if ($_REQUEST['short_action'] == 'delete') {
            $image = $wpdb->get_var("SELECT TemplatesGraphicsPath FROM st_coupon_template_graphics WHERE CouponTemplateGraphicsID = " . $_POST['id']);
            $pdf = $wpdb->get_var("SELECT TemplatesPDFPath FROM st_coupon_template_graphics WHERE CouponTemplateGraphicsID = " . $_POST['id']);
            $stPostcardsClass->deleteGallery($image);
            $stPostcardsClass->deleteGallery($pdf);
            $wpdb->query("DELETE FROM st_coupon_template_graphics WHERE CouponTemplateGraphicsID = " . $_POST['id'] . " AND user_id = " . $current_user->ID);
            $arg = array(
                'status' => 'success',
                'message' => __('Delete successful', $config['plugin_name'])
            );
            echo $this->functions->sendMessage(json_encode($arg));
        }

        $args = array();
        $args['where'] = ' user_id = ' . $_GET['user'];
        $cur_page = $_REQUEST['cur_page'] ? $_REQUEST['cur_page'] : 1;
        $limit = $this->config['per_page'];
        $start = ($cur_page - 1) * $limit;

        $sort = $_REQUEST['sort'] ? $_REQUEST['sort'] : 'id';
        $sort_type = $_REQUEST['sort_type'] ? $_REQUEST['sort_type'] : 'DESC';
        if ($_REQUEST['sort']) {
            $args['order'] = array($sort, $sort_type);
        }
        $args['limit'] = array($start, $limit);

        $results = $stFacebookToolbox_model->getRecords($args);
        $total = $wpdb->get_var("SELECT COUNT(*) FROM st_coupon_template_graphics user_id = " . $_POST['user']);
        $pagination = $this->functions->pagination($start, $limit, $total, $cur_page, $this->actionName);

        $columns = array(
            'CouponTemplateGraphicsID' => __('ID', $this->config['plugin_name']),
            'TemplatesGraphicsName' => __('Name', $this->config['plugin_name']),
            'TemplatesGraphicsPath' => __('Picture', $this->config['plugin_name']),
        );
        register_column_headers('stFacebookToolbox_stFacebookToolbox', $columns);

        //initialize variable to view
        $this->view->results = $results;
        $this->view->pagination = $pagination;
    }

    public function coupon_contract_overview() {
        global $wpdb;
        if (isset($_POST['data'])) {
            $activated = explode('.', $_POST['data']['activated']);
            $data['activated'] = $activated[2] . '-' . $activated[1] . '-' . $activated[0];
            $expire = explode('.', $_POST['data']['expire']);
            $data['expire'] = $expire[2] . '-' . $expire[1] . '-' . $expire[0];
            $data['type'] = $_POST['data']['revenue'];
            $data['amount'] = $_POST['data']['fee'];
            $data['contract'] = $_POST['data']['contract'];
            $data['user_id'] = $_POST['data']['user_id'];
            $data['currency'] = $_POST['currency']['currency'];
            if ($wpdb->get_var("SELECT COUNT(*) FROM st_coupon_contract WHERE user_id = " . $_POST['data']['user_id']) == 0)
                $wpdb->insert('st_coupon_contract', $data);
            else
                $wpdb->update('st_coupon_contract', $data, array('user_id' => $_POST['data']['user_id']));
            $arg = array(
                'status' => 'success',
                'message' => __('Saved successful', $config['plugin_name'])
            );
            echo $this->functions->sendMessage(json_encode($arg), 'coupon_contract_overview&user=' . $_POST['data']['user_id']);
            die;
        }
        $this->view->company_info = get_user_meta($_POST['user'], 'company_info');
        $company_info = get_user_meta($_POST['user'], 'company_info');
        $user = get_userdata($_POST['user']);
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Contract overview (' . $company_info[0]['company_name'] . ')';
        $this->view->user = $user->user_login;
        $this->view->user_id = $_POST['user'];
        $this->view->contract_result = $wpdb->get_row("SELECT * FROM st_coupon_contract WHERE user_id = " . $_POST['user']);
    }

    public function coupon_facebook_setting() {
        global $wpdb, $current_user;
        $user = get_userdatabylogin($_POST['user']);
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Facebook Settings';
        if (isset($_POST['data'])) {
            $data['app_id'] = $_POST['data']['app_id'];
            $data['secrect'] = $_POST['data']['secrect'];
            $data['user_id'] = $_POST['data']['user_id'];
            if ($wpdb->get_var("SELECT COUNT(*) FROM st_coupons_facebook_setting WHERE user_id = {$_POST['data']['user_id']}") > 0) {
                $wpdb->update('st_coupons_facebook_setting', $data, array('user_id' => $_POST['data']['user_id']));
            } else {
                $wpdb->insert('st_coupons_facebook_setting', $data);
            }
            $arg = array(
                'status' => 'success',
                'message' => __('Setting saved successful', $config['plugin_name'])
            );
            echo $this->functions->sendMessage(json_encode($arg), 'coupon_facebook_setting&user=' . $_POST['data']['username']);
        }

        $this->view->user = $user->ID;
        $this->view->username = $_POST['user'];
        $this->view->user_result = $wpdb->get_row("SELECT * FROM st_coupons_facebook_setting WHERE user_id = {$user->ID}");
    }

    //--- End - Coupon

    public function index() {
        $option = $this->option;
        $fbCmsData = $option['fbCmsData'];
//        var_dump($option);
        //initialize variable to view
        $this->view->option = $option;
        $this->view->fbCmsData = $fbCmsData;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Dashboard';
    }

    public function setting() {
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'General settings';
    }

    public function userList() {
        $filter_company_name = isset($_POST['filter_company_name']) ? $_POST['filter_company_name'] : 'all';
        $filter_user_level = isset($_POST['filter_user_level']) ? $_POST['filter_user_level'] : 'all';
        $st_pluginperm_model = $this->loadmodel("st_pluginperm");
        $socialUser_model = $this->loadmodel("st_social_user");

        // short action handle
        if (!empty($_POST['plugin'])) {
            $data = array(
                'plugin_name' => $_POST['plugin'],
                'user_id' => $_POST['user_id']
            );
            if ($_POST['value'] == 1) {                
                $arg = $st_pluginperm_model->enablePlugin($data);  
                if($_POST['plugin'] == "stFacebookToolbox") {
                    $data['plugin_name'] = 'stContestToolbox';
                    $st_pluginperm_model->enablePlugin($data); 
//                    die("call me");
                }
            } else {
                $arg = $st_pluginperm_model->disablePlugin($data);
                
                if($_POST['plugin'] == "stFacebookToolbox") {
                    $data['plugin_name'] = 'stContestToolbox';
                    $st_pluginperm_model->enablePlugin($data); 
                }
            }

            echo json_encode($arg);
            die;
        }

        if ($_REQUEST['short_action'] == 'delete') {
            $data = array(
                'user_id' => $_REQUEST['id']
            );
            if ($socialUser_model->removeUser($data)) {
                $arg = array(
                    'status' => 'success',
                    'message' => __('Remove successful', $config['plugin_name'])
                );
                echo $this->functions->sendMessage(json_encode($arg));
            } else {
                $arg = array(
                    'status' => 'error',
                    'message' => __('Remove unsuccessful', $config['plugin_name'])
                );
                echo $this->functions->sendMessage(json_encode($arg));
            }
        }

        $args = array();

        $cur_page = $_REQUEST['cur_page'] ? $_REQUEST['cur_page'] : 1;
        $limit = $this->config['per_page'];
        $start = ($cur_page - 1) * $limit;

        $sort = $_REQUEST['sort'] ? $_REQUEST['sort'] : 0;
        $sort_type = $_REQUEST['sort_type'] ? $_REQUEST['sort_type'] : 0;
        if ($_REQUEST['sort']) {
            $args['order'] = array($sort, $sort_type);
        } else {
            $args['order'] = array('parent_id', 'ASC');
        }
        $args['limit'] = array($start, $limit);
        $args['fields'] = array('user.user_id user_id, user.*, GROUP_CONCAT("",perm.plugin_name) plugin_name');
        $args['group_by'] = 'user_id';
        $user = get_current_user_id();
        if (!user_can($user, 'edit_dashboard')) {
            $args['where'] = " user.parent_id = $user";
        }
        $results = $st_pluginperm_model->getRecords($args);
        $args['limit'] = array();
        $total = $st_pluginperm_model->countRecords($args);

        $pagination = $this->functions->pagination($start, $limit, $total, $cur_page, $this->actionName);

        $columns = array(
            'user_login' => __('User name', $this->config['plugin_name']),
            'parent_id' => __('Company name', $this->config['plugin_name']),
            'user_level' => __('User level', $this->config['plugin_name'])
        );
        $addons = $this->functions->getAddOns();
        if (count($addons) > 0) {
            foreach ($addons as $key => $value) {
                if (!empty($key))
                    $columns[$key] = substr ($key, 2); //str_replace('st', '', $key);
            }
        }else {
            $columns['none'] = 'No Addons';
        }
        register_column_headers('stSocialMediaToolbox_st_pluginperm', $columns);
        $company_name = array();
        foreach ($results as $key1 => &$result) {
            $user_data = get_user_by('id', $result->user_id);
            if ($user_data && is_array($user_data->wp_capabilities)) {
                foreach ($user_data->wp_capabilities as $key => $value) {
                    $role = $key;
                }
            }
            if ($result->parent_id) {
                $user_meta = get_user_meta($result->parent_id, 'company_info', true);
            } else {
                $user_meta = get_user_meta($result->user_id, 'company_info', true);
            }
            if (!in_array($user_meta['company_name'], $company_name) && !empty($user_meta['company_name'])) {
                $company_name[] = $user_meta['company_name'];
            }
            if ($filter_company_name != 'all' && $user_meta['company_name'] != $filter_company_name) {
                unset($results[$key1]);
            }

            if ($filter_user_level != 'all' && $role != $filter_user_level) {
                unset($results[$key1]);
            }
        }

        //initialize variable to view
        $this->view->results = $results;
        $this->view->addons = $addons;
        $this->view->pagination = $pagination;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'User list';
        $this->view->iconNew = 'Add new user';
        $this->view->iconNewFunction = "jQuery.prettyPhoto.loadPage('userAddNew', '');";
        $this->view->company_name = $company_name;
        $this->view->filter_company_name = $filter_company_name;
        $this->view->filter_user_level = $filter_user_level;
    }

    public function userAddNew() {
        $socialUser_model = $this->loadmodel("st_social_user");
        $returnAction = empty($_POST['return_action']) ? 'userList' : $_POST['return_action'];
        $this->view->headIcon = 'icon_re';
        $this->view->returnAction = $returnAction;
        //$this->view->headTitle1 = 'Add new user';
        $users = get_users_of_blog();

        $args = array();

        $args['fields'] = array('b.ID id');

        $results = $socialUser_model->getRecords($args);
        $socialUsers = array();
        foreach ($results as $value) {
            $socialUsers[] = $value->id;
        }
        $columns = array(
            'user_login' => __('User name', $this->config['plugin_name']),
            'user_email' => __('User email', $this->config['plugin_name']),
            'add_new' => __('Add new', $this->config['plugin_name'])
        );
        register_column_headers('stSocialMediaToolbox_st_social_user', $columns);
        //initialize variable to view
        $this->view->users = $users;
        $this->view->socialUsers = $socialUsers;

        if (!empty($_POST['user_id'])) {
            $user_email = get_user_by('id', $_POST['user_id']);
            $user_email = $user_email->user_email;

            $data = array(
                'user_id' => $_POST['user_id'],
                'user_email' => $user_email
            );
            if ($_POST['value'] == 1) {
                $arg = $socialUser_model->addUser($data);
            } else {
                $arg = $socialUser_model->removeUser($data);
            }

            echo json_encode($arg);
            die;
        }
    }

    public function userEdit() {
        $socialUser_model = $this->loadmodel("st_social_user");
        $args = array();
        $args['where'] = " a.parent_id = 0";
        $users = $socialUser_model->getRecords($args);

        $results = '';
        if (isset($_REQUEST['id'])) {
            $id = $_REQUEST['id'];
            $args = array();
            $args['where'] = " a.id = $id";
            $results = $socialUser_model->getRecords($args);
        }
        $result = $results[0];
        //initialize variable to view
        $this->view->result = $result;
        $this->view->users = $users;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'New user';
        $this->view->headTitle2 = 'Edit user';


        // Handle post
        if ($_POST['data']) {
            $data = $_POST['data'];
            if (empty($data['ID'])) {
                $user_id = wp_insert_user($data);
            } else {
                if (empty($data['user_pass'])) {
                    unset($data['user_pass']);
                } else {
                    $data['user_pass'] = wp_hash_password($data['user_pass']);
                    $arg = array(
                        'status' => 'success',
                        'message' => __('Update password successful', $config['plugin_name'])
                    );
                }

                $user_id = wp_insert_user($data);
            }
            if (is_wp_error($user_id)) {
                $arg = $this->functions->getErrorMessage($user_id);
            } else {
                $meta = $_POST['meta'];
                $data1 = array(
                    'user_id' => $user_id,
                    'user_email' => $data['user_email'],
                    'parent_id' => $_POST['parent_id']
                );
                $data1['id'] = isset($_POST['social_user_id']) ? $_POST['social_user_id'] : NULL;
                if (empty($arg))
                    $arg = $socialUser_model->addUser($data1, $meta);
                else
                    $socialUser_model->addUser($data1, $meta);
            }

            if (!empty($_POST['send_email'])) {
                $content = "<h2>Your information:</h2>"
                        . "<div style='margin-left:10px'>"
                        . "User name: " . $data['user_login'] . "<br/>"
                        . "Password: " . $data['user_pass'] . "<br/>"
                        . "</div>"
                        . "<h2>Website url:</h2> " . home_url('/wp-login.php')
                ;

                /* -----------------------Send confirm email---------------------------- */
                $to = $data['user_email'];
                $subject = 'Your account have been created';
                $content = $content;

                $headers = 'MIME-Version: 1.0' . "\r\n";
                $headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
                $mail = wp_mail($to, $subject, $content, $headers);
            }

            echo json_encode($arg);
            die;
        }
    }

    public function settingEmail() {
        $data['settingEmail'] = $_REQUEST['data'];
        if ($_REQUEST['data']) {
            if ($this->updateGeneralOption($data)) {
                $arg = array(
                    'status' => 'success',
                    'message' => __('Update option successful', $config['plugin_name'])
                );
                echo json_encode($arg);
                die;
            } else {
                $arg = array(
                    'status' => 'error',
                    'message' => __('Update option unsuccessful', $config['plugin_name'])
                );
                echo json_encode($arg);
                die;
            }
        }
        $option = $this->getFullOptions();
        $this->view->option = $option['settingEmail'];
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Email settings';
    }

    public function systemLog() {
        //initialize variable to view
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'System log';
        $this->view->iconNew = '';
    }

    public function cronjobLog() {
        $filter_cronjob_name = isset($_POST['filter_cronjob_name']) ? $_POST['filter_cronjob_name'] : 'all';
        $status = isset($_POST['status']) ? $_POST['status'] : 'all';
        $st_cronjob_log_model = $this->loadmodel("st_cronjob_log");

        // short action handle
        if ($_REQUEST['short_action'] == 'delete') {
            if ($st_cronjob_log_model->deleteRecords($_REQUEST['id'])) {
                $arg = array(
                    'status' => 'success',
                    'message' => __('Remove successful', $config['plugin_name'])
                );
                echo $this->functions->sendMessage(json_encode($arg));
            } else {
                $arg = array(
                    'status' => 'error',
                    'message' => __('Remove unsuccessful', $config['plugin_name'])
                );
                echo $this->functions->sendMessage(json_encode($arg));
            }
        }

        $args = array();

        $cur_page = $_REQUEST['cur_page'] ? $_REQUEST['cur_page'] : 1;
        $limit = $this->config['per_page'];
        $start = ($cur_page - 1) * $limit;

        $sort = $_REQUEST['sort'] ? $_REQUEST['sort'] : 0;
        $sort_type = $_REQUEST['sort_type'] ? $_REQUEST['sort_type'] : 0;
        if ($_REQUEST['sort']) {
            $args['order'] = array($sort, $sort_type);
        } else {
            $args['order'] = array('ctime', 'DESC');
        }
        $args['limit'] = array($start, $limit);
        $args['where'] = ' 1=1';

        if ($filter_cronjob_name != 'all') {
            $args['where'] .= " AND `cronjob_name` like('{$filter_cronjob_name}')";
        }
        if ($status != 'all') {
            $args['where'] .= " AND `status` = {$status}";
        }
        $results = $st_cronjob_log_model->getRecords($args);
        $args['limit'] = array();
        $total = $st_cronjob_log_model->countRecords($args);
        $pagination = $this->functions->pagination($start, $limit, $total, $cur_page, $this->actionName);

        $columns = array(
            'id' => __('Log ID', $this->config['plugin_name']),
            'cronjob_name' => __('Cronjob name', $this->config['plugin_name']),
            'toolbox_name' => __('Toolbox name', $this->config['plugin_name']),
            'url' => __('File url', $this->config['plugin_name']),
            'status' => __('Status', $this->config['plugin_name']),
            'ctime' => __('Excute time', $this->config['plugin_name']),
        );

        register_column_headers('stSocialMediaToolbox_st_cronjob_log', $columns);
        $cronjob_name = $st_cronjob_log_model->getCronjobName();

        //initialize variable to view
        $this->view->results = $results;
        $this->view->pagination = $pagination;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Cronjob log';
        $this->view->iconNew = '';
        $this->view->iconNewFunction = "";
        $this->view->filter_cronjob_name = $filter_cronjob_name;
        $this->view->cronjob_name = $cronjob_name;
    }

    public function user_logging() {
        global $wpdb;
        $st_cronjob_log_model = $this->loadmodel("st_user_log");
        if ($_REQUEST['short_action'] == 'delete') {
            if ($st_cronjob_log_model->deleteRecords($_REQUEST['id'])) {
                $arg = array(
                    'status' => 'success',
                    'message' => __('Remove successful', $config['plugin_name'])
                );
                echo $this->functions->sendMessage(json_encode($arg));
            } else {
                $arg = array(
                    'status' => 'error',
                    'message' => __('Remove unsuccessful', $config['plugin_name'])
                );
                echo $this->functions->sendMessage(json_encode($arg));
            }
        }

        $args = array();
        $username = (isset($_POST['username']) && $_POST['username'] != 'all') ? ' AND username = "' . $_POST['username'] . '"' : '';
        $ip = (isset($_POST['ip']) && $_POST['ip'] != 'all') ? ' AND ip = "' . $_POST['ip'] . '"' : '';
        $browser = (isset($_POST['browser']) && $_POST['browser'] != 'all') ? ' AND browser = "' . $_POST['browser'] . '"' : '';
        $os = (isset($_POST['os']) && $_POST['os'] != 'all') ? ' AND os = "' . $_POST['os'] . '"' : '';
        $status = (isset($_POST['status']) && $_POST['status'] != 'all' ) ? ' AND status = "' . $_POST['status'] . '"' : '';
        $args['where'] = '1=1 ' . $username . $ip . $browser . $os . $status;
        $cur_page = $_REQUEST['cur_page'] ? $_REQUEST['cur_page'] : 1;
        $limit = $this->config['per_page'];
        $start = ($cur_page - 1) * $limit;

        $sort = $_REQUEST['sort'] ? $_REQUEST['sort'] : 0;
        $sort_type = $_REQUEST['sort_type'] ? $_REQUEST['sort_type'] : 0;
        if ($_REQUEST['sort']) {
            $args['order'] = array($sort, $sort_type);
        } else {
            $args['order'] = array('date', 'DESC');
        }
        $args['limit'] = array($start, $limit);
        $results = $st_cronjob_log_model->getRecords($args);
        $args['limit'] = array();
        $total = $st_cronjob_log_model->countRecords($args);
        $pagination = $this->functions->pagination($start, $limit, $total, $cur_page, $this->actionName);

        $columns = array(
            'date' => __('Date/Time', $this->config['plugin_name']),
            'ip' => __('IP', $this->config['plugin_name']),
            'username' => __('Username', $this->config['plugin_name']),
            'browser' => __('Browser', $this->config['plugin_name']),
            'os' => __('OS', $this->config['plugin_name']),
            'status' => __('Status', $this->config['plugin_name']),
        );

        register_column_headers('stSocialMediaToolbox_st_cronjob_log', $columns);
        $this->view->results = $results;
        $this->view->pagination = $pagination;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'User Access Log';
        $this->view->username = $wpdb->get_results("SELECT * FROM wp_st_user_log WHERE 1=1 " . $ip . $browser . $os . " GROUP BY username");
        $this->view->ip = $wpdb->get_results("SELECT * FROM wp_st_user_log WHERE 1=1 " . $username . $browser . $os . " GROUP BY ip");
        $this->view->browser = $wpdb->get_results("SELECT * FROM wp_st_user_log WHERE 1=1 " . $username . $ip . $os . " GROUP BY browser");
        $this->view->os = $wpdb->get_results("SELECT * FROM wp_st_user_log WHERE 1=1 " . $username . $ip . $browser . " GROUP BY os");
        $this->view->user_os = $_POST['os'];
        $this->view->user_browser = $_POST['browser'];
        $this->view->user = $_POST['username'];
        $this->view->user_ip = $_POST['ip'];
        $this->view->status = $_POST['status'];
    }

    public function help() {
        $socialUser_model = $this->loadmodel("st_social_user");
        $userID = get_current_user_id();
        $userData = get_user_by('id', $userID);
        if ($userData) {
            foreach ($userData->wp_capabilities as $key => $value) {
                $role = $key;
            }
        }
        switch ($role) {
            case 'administrator':
                $role = 'Master admin';
                break;
            case 'editor':
                $role = 'Client admin';
                break;
            default:
                $role = 'Regular user';
                break;
        }
        if ($result->parent_id) {
            $user_meta = get_user_meta($result->parent_id, 'company_info', true);
        } else {
            $user_meta = get_user_meta($result->user_id, 'company_info', true);
        }
        $results = '';
        $args = array();
        $args['where'] = " a.user_id = $userID";
        $results = $socialUser_model->getRecords($args);

        $result = $results[0];
        if ($result->parent_id) {
            $user_meta = get_user_meta($result->parent_id, 'company_info', true);
        } else {
            $user_meta = get_user_meta($result->user_id, 'company_info', true);
        }
        $clientName = $user_meta['company_name'];

        $addons = $this->functions->getAddOns();


        $this->view->userData = $userData;
        $this->view->role = $role;
        $this->view->clientName = $clientName;
        $this->view->addons = $addons;

        if ($_POST['data']) {

            function phpmailerInit($phpmailer) {
                $data = $_POST['data'];
                $phpmailer->IsSMTP();
                $phpmailer->Host = 'smtp.domeneshop.no';
                $phpmailer->Port = '25';
                $phpmailer->SMTPAuth = 'true';
//                $phpmailer->SMTPSecure = 'ssl';
                $phpmailer->Username = 'slopetracker8';
                $phpmailer->Password = 'Lillehammer2010';
                $phpmailer->Body = do_shortcode($phpmailer->Body);
                $phpmailer->From = $data['user_email'];
                $phpmailer->FromName = $data['user_name'];
            }

            add_action('phpmailer_init', 'phpmailerInit', 100, 1);
            $browser = stfunctions_2_1::getBrowerType();
            $data = $_POST['data'];
            $to = 'support@slopetracker.no, ngthaibinh86@gmail.com';
            $subject = 'SMT Support: ' . $data['subject'];

            $content = "<h2>Support request information:</h2>\r\n"
                    . "<div style='margin-left:10px'>"
                    . "User name: " . $data['user_name'] . "<br/>\r\n"
                    . "User email: " . $data['user_email'] . "<br/>\r\n"
                    . "User role: " . $data['user_role'] . "<br/>\r\n"
                    . "Client name: " . $data['client_name'] . "<br/>\r\n"
                    . "Toolbox name: " . $data['toolbox_name'] . "<br/>\r\n"
                    . "Browser: " . $browser['browser'] . "<br/>\r\n"
                    . "Browser version: " . $browser['version'] . "<br/>\r\n"
                    . "Support request: " . nl2br($data['description']) . "<br/>\r\n"
                    . "</div>"
            ;

            $headers = 'MIME-Version: 1.0' . "\r\n";
            $headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
            $mail = wp_mail($to, $subject, $content, $headers);
//            var_dump($mail);die;
            if ($mail) {
                $arg = array(
                    'status' => 'success',
                    'message' => __('Submit successfull', $config['theme_name'])
                );
            } else {
                $arg = array(
                    'status' => 'error',
                    'message' => __('Submit unsuccessfull' . $mail, $config['theme_name'])
                );
            }
            echo $this->functions->sendMessage(json_encode($arg));
            die;
        }
    }

    public function appPermission() {
        $st_appperm_model = $this->loadmodel("st_appperm");
        $socialUser_model = $this->loadmodel("st_social_user");

        // short action handle
        if (!empty($_POST['plugin'])) {
            $data = array(
                'app_name' => $_POST['plugin'],
                'user_id' => $_POST['user_id']
            );
            if ($_POST['value'] == 1) {
                $arg = $st_appperm_model->enableApplication($data);
            } else {
                $arg = $st_appperm_model->disableApplication($data);
            }

            echo json_encode($arg);
            die;
        }

        $args = array();

        $cur_page = $_REQUEST['cur_page'] ? $_REQUEST['cur_page'] : 1;
        $limit = 25;
        $start = ($cur_page - 1) * $limit;

        $sort = $_REQUEST['sort'] ? $_REQUEST['sort'] : 0;
        $sort_type = $_REQUEST['sort_type'] ? $_REQUEST['sort_type'] : 0;
        if ($_REQUEST['sort']) {
            $args['order'] = array($sort, $sort_type);
        } else {
            $args['order'] = array('parent_id', 'ASC');
        }
        $args['limit'] = array($start, $limit);
        $args['fields'] = array('wp_user.user_login user_login, user.user_id user_id, user.*, GROUP_CONCAT("",app.app_name) app_name');
        $args['group_by'] = 'user_id';
        $user = get_current_user_id();
        if (!user_can($user, 'edit_dashboard')) {
            $args['where'] = " user.parent_id = $user";
        }
//        var_dump($args);
        $results = $st_appperm_model->getRecords($args);
//        var_dump($results);
        $args['limit'] = array();
        $total = $st_appperm_model->countRecords($args);

        $pagination = $this->functions->pagination($start, $limit, $total, $cur_page, $this->actionName);

        $columns = array(
            'user_login' => __('User name', $this->config['plugin_name']),
        );
        $toolboxApp = $this->config['toolboxApplication'];
        if (count($toolboxApp) > 0) {
            foreach ($toolboxApp as $key => $value) {
                if (!empty($value))
                    $columns[$key] = $value;
            }
        }else {
            $columns['none'] = 'No Addons';
        }
        register_column_headers('stSocialMediaToolbox_st_appperm', $columns);

        //initialize variable to view        
        $this->view->results = $results;
        $this->view->toolboxApp = $toolboxApp;
        $this->view->pagination = $pagination;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Applications';
        $this->view->iconNew = 'Add new user';
//        $this->view->iconNewFunction = "";
    }

    public function ajaxPostAction() {
        $save_type = $_POST['type'];
        $post_card = $_POST['post_card'];
        //Uploads
        if ($save_type == 'upload') {
            $clickedID = $_POST['data']; // Acts as the name
            $filename = $_FILES[$clickedID];
            $filename['name'] = preg_replace('/[^a-zA-Z0-9._\-]/', '', $filename['name']);
            $override['test_form'] = false;
            $override['action'] = 'wp_handle_upload';
            $uploaded_file = wp_handle_upload($filename, $override);
            if (substr($filename['name'], -4, 4) == '.pdf') {
                echo $uploaded_file['url'] . "|*|" . $uploaded_file['file'];
                die;
            }
            list($width, $height) = getimagesize($uploaded_file['file']);
            if ($_POST['thumbnail_width'] != '' && $width > $_POST['thumbnail_width']) {
                $max_w = $_POST['thumbnail_width'];
                $max_h = round(($max_w * $height) / $width);
                if (isset($uploaded_file['file'])) {
                    $thumbnail = image_resize($uploaded_file['file'], $max_w, $max_h, true, 'thumb');
                    $thumbnail_url = $upload_dir_url . basename($thumbnail);
                }
            } else {
                if ($_POST['thumbnail_height'] != '') {
                    $max_h = $_POST['thumbnail_height'];
                    $max_w = round(($max_h * $width) / $height);
                    if (isset($uploaded_file['file'])) {
                        $thumbnail = image_resize($uploaded_file['file'], $max_w, $max_h, true, 'thumb');
                        $thumbnail_url = $upload_dir_url . basename($thumbnail);
                    }
                }
            }

            if ($post_card) {
                $max_w = 642;
                $max_h = 431;
                if (isset($uploaded_file['file'])) {
                    $thumbnail = $this->functions->image_zoom($uploaded_file['file'], $max_w, $max_h, false, 'large');
                }
            }

            if (!empty($uploaded_file['error'])) {
                echo 'Upload Error: ' . $uploaded_file['error'] . "|*| Upload Error";
                die;
            } else {
                echo $uploaded_file['url'] . "|*|" . $uploaded_file['file'];
                die;
            } // Is the Response
        } elseif ($save_type == 'image_remove') {
            $file = $_POST['file']; // Acts as the name
            $img_name = basename($file);
            $img_name = explode('.', $img_name);
            $img_name = $img_name[0];
            $file_thumb = str_replace($img_name, $img_name . '-thumb', $file);
            $file_large = str_replace($img_name, $img_name . '-large', $file);
            unlink($file);
            if (substr($file, -4, 4) != '.pdf') {
                unlink($file_thumb);
                unlink($file_large);
            }
        }
    }

    //Binh Add: 15-12-2011
    public function setCmsUrl() {
        global $wpdb;
        $userID = $_POST['userID'];
        $option = $this->getOption('', $userID);
//        var_dump($option);
        $check = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}st_app_perm WHERE app_name = '{$_POST['app']}' AND user_id = {$userID}");
        if (!$check) {
            $arg = array(
                'status' => 'error',
                'message' => __("User does not have permission", $config['plugin_name'])
            );
            echo $this->functions->sendMessage(json_encode($arg), 'appPermission');
            echo "<script type='text/javascript'>jQuery.prettyPhoto.close()</script>";
            die;
        }
        if (!empty($userID)) {

            $fbCmsData = $option['fbCmsData'];
            $this->view->fbCmsData = $fbCmsData;
            $this->view->userID = $userID;
            $this->view->app = $_POST['app'];
        }
        if (!empty($_POST['data'])) {
            $data = $_POST['data'];
            $fbCmsUrl = $data['fbCmsUrl'];
            $data = array(
                'fbCmsData' => $data
            );
            if (!empty($userID))
                $result = $this->updateOption($data, '', $userID);
        }
    }

    public function deleteOldLog() {
        $st_cronjob_log_model = $this->loadmodel("st_cronjob_log");
        $st_user_log_model = $this->loadmodel("st_user_log");

        if ($_POST['deleteOldLog'] == 1) {
            $result1 = $st_user_log_model->cleanLog();
            $result2 = $st_cronjob_log_model->cleanLog();
            if ($result1 && $result2) {
                $arg = array(
                    'status' => 'success',
                    'message' => __("Delete old log entries successful", $config['plugin_name'])
                );
                echo $this->functions->sendMessage(json_encode($arg));
            } else {
                $arg = array(
                    'status' => 'error',
                    'message' => __("Delete old log entries unsuccessful", $config['plugin_name'])
                );
                echo $this->functions->sendMessage(json_encode($arg));
            }
        }
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Delete old log entries';
    }

    public function userInfo() {
        $socialUser_model = $this->loadmodel("st_social_user");
        $args = array();
        $args['where'] = " a.parent_id = 0";
        $users = $socialUser_model->getRecords($args);

        $results = '';
        $id = get_current_user_id();
        $args = array();
        $args['where'] = " a.user_id = $id";
        $results = $socialUser_model->getRecords($args);

        $result = $results[0];
        //initialize variable to view
        $this->view->result = $result;
        $this->view->users = $users;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle2 = 'Contact information';
        $this->view->headTitle1 = 'Contact information';


        // Handle post
        if ($_POST['data']) {
            $data = $_POST['data'];
            if (empty($data['user_pass'])) {
                unset($data['user_pass']);
            } else {
                $data['user_pass'] = wp_hash_password($data['user_pass']);
                $arg = array(
                    'status' => 'success',
                    'message' => __('Update password successful', $config['plugin_name'])
                );
            }
            $user_id = wp_update_user($data);
            if (is_wp_error($user_id)) {
                $arg = $this->functions->getErrorMessage($user_id);
            } else {
                $meta = $_POST['meta'];
                $data1 = array(
                    'user_id' => $user_id,
                    'user_email' => $data['user_email'],
                    'parent_id' => $_POST['parent_id']
                );
                $data1['id'] = isset($_POST['social_user_id']) ? $_POST['social_user_id'] : NULL;
                if (empty($arg))
                    $arg = $socialUser_model->addUser($data1, $meta);
                else
                    $socialUser_model->addUser($data1, $meta);
            }
            echo $this->functions->sendMessage(json_encode($arg));
            die;
        }
    }

    public function userInvoice() {
        
    }

    public function cronjobWeeklyReport() {
        $socialUser_model = $this->loadmodel("st_user_log");
        $st_cronjob_log_model = $this->loadmodel("st_cronjob_log");
        $loginResults = $socialUser_model->numberOfLogin();
        $mostFiveLogin = $socialUser_model->getMostFiveLogin();
        $numberOfRegisterUser = $socialUser_model->numberOfRegisterUser();
        $dbSize = $socialUser_model->getDBSize();
        $totalLogRow = $socialUser_model->totalLogRow();
        $cronjobResults = $st_cronjob_log_model->numberOfExecuted();
//        var_dump($cronjobResults);
        $cronjobFailExecuted = $st_cronjob_log_model->getAllFailExecuted();
        $fiveLogin = '';
        if (count($mostFiveLogin) >= 1) {
            foreach ($mostFiveLogin as $key => $value) {
                $fiveLogin .= $value->username . ' (' . $value->num . ')' . ' | ';
            }
        }
        $failExecuted = '';
        if (count($cronjobFailExecuted) >= 1) {
            foreach ($cronjobFailExecuted as $key => $value) {
                $failExecuted .= "- {$value->name} | {$value->num2} | {$value->num1}  <br/>";
            }
        }
        $dayOfPreWeek = mktime(0, 0, 0, date('m'), date('d')-7, date('Y'));
        $numberOfday = date('w', $dayOfPreWeek);
        
        $dis = $numberOfday - 1;
        $startPreWeek = $dayOfPreWeek - ($dis * 24 * 60 * 60);
        $endPreWeek = date('d-m-Y', $startPreWeek + (6 * 24 * 60 * 60));
        $startPreWeek = date('d-m-Y', $startPreWeek);
        /* -----------------------Send report email---------------------------- */
        $content = "<h2>Weekly system log report - SMT</h2>"
                . "<div style='margin-left:15px'>"
                . "-----------------------------------<br/>"
                . "User Statistics<br/>"
                . "-----------------------------------<br/>"
                . "Number of sucsesfull log-ins: " . $loginResults['success'] . "<br/>"
                . "Number of failed log-ins: " . $loginResults['fail'] . "<br/>"
                . "List the 5 most logged in users: " . $fiveLogin . "<br/>"
                . "Number of registered users: " . $numberOfRegisterUser . "<br/>"
                . "-----------------------------------<br/><br/>"
                . "-----------------------------------<br/>"
                . "Database statistics<br/>"
                . "-----------------------------------<br/>"
                . "Size (in MB) of the database: " . $dbSize . "<br/>"
                . "Total number of records in system log: " . $totalLogRow . "<br/>"
                . "-----------------------------------<br/><br/>"
                . "-----------------------------------<br/>"
                . "Cron job statistics<br/>"
                . "-----------------------------------<br/>"
                . "Number of cron-job executed sucsesfull: " . $cronjobResults['success'] . "<br/>"
                . "Number of cron-job executed fail: " . $cronjobResults['fail'] . "<br/>"
                . "-----------------------------------<br/><br/>"
                . "-----------------------------------<br/>"
                . "Cron job log for $startPreWeek - $endPreWeek <br/>"
                . "-----------------------------------<br/>"
                . $failExecuted
                . "</div>"
        ;
        
        
        
        
        $to = $this->config['reportToList'];
        $subject = 'Weekly system log report - SMT From: '.$startPreWeek.' To: '.$endPreWeek;
        $content = $content;
//        echo $content.$subject;
//        die;
        $headers = 'MIME-Version: 1.0' . "\r\n";
        $headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
        $mail = wp_mail($to, $subject, $content, $headers);
        if ($mail)
            echo 'true';
        else
            echo 'false';
        die;
        // END
    }

}

?>